package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
)

//go get -u github.com/mattn/go-sqlite3

const files_root_path = "files"

func main() {
	DBInit()
	// 网页
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/list", listHandler)
	http.HandleFunc("/history", historyHandler)

	// post请求
	http.HandleFunc("/upload", uploadHandle)

	fs := http.FileServer(http.Dir("static/"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	// 上传的图片访问路径
	fs_files := http.FileServer(http.Dir(files_root_path + "/"))
	http.Handle("/"+files_root_path+"/", http.StripPrefix("/"+files_root_path+"/", fs_files))

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("Defaulting to port %s", port)
	}
	log.Println("-----------------")
	log.Printf("Listening on port %s", port)
	log.Printf("Open http://localhost:%s in the browser", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

/*
主页
*/
var tmpl_index, _ = template.ParseFiles("template/root.html", "template/index.html")

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	err := tmpl_index.Execute(w, nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

var tmpl_list, _ = template.ParseFiles("template/root.html", "template/list.html")

func listHandler(w http.ResponseWriter, r *http.Request) {
	err := tmpl_list.Execute(w, nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

var tmpl_history, _ = template.ParseFiles("template/root.html", "template/history.html")

func historyHandler(w http.ResponseWriter, r *http.Request) {
	err := tmpl_history.Execute(w, nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
